package com.wzk.dwetl.utils

import java.io.{ByteArrayInputStream, ByteArrayOutputStream, DataInputStream, DataOutputStream, ObjectOutputStream}

import org.roaringbitmap.RoaringBitmap

import scala.collection.mutable

object RrUtils {

  //将RoaringBitmap对象序列化字节数组
  def ser(rr: RoaringBitmap): Array[Byte] = {
    val ba = new ByteArrayOutputStream()
    val dout = new DataOutputStream(ba);
    rr.serialize(dout)
    ba.toByteArray
  }

  //将字节数组反序列化RoaringBitmap对象
  def de(arr: Array[Byte]): RoaringBitmap = {
    val rr = new RoaringBitmap()
    val in = new ByteArrayInputStream(arr)
    val dis = new DataInputStream(in)
    rr.deserialize(dis)
    rr
  }

  //去bitmap中1的个数(基数)
  def getCard(bits: Array[Byte]): Int = {
    //获取RoaringBitmap对象
    val rb = new RoaringBitmap()
    //将字节数组封装为ByteArrayInputStream对象
    val in = new ByteArrayInputStream(bits)
    val dis = new DataInputStream(in)
    rb.deserialize(dis)
    rb.getCardinality
  }

  val toBitmap = (ids: mutable.WrappedArray[Int]) => {
    val bitmap = RoaringBitmap.bitmapOf(ids: _*)
    val bout = new ByteArrayOutputStream()
    //利用jdk自己的objectoutputstream序列化的效率较低
    /*val objOutput = new ObjectOutputStream(bout)
    objOutput.writeObject(bitmap)*/
    val dataOutput = new DataOutputStream(bout)
    bitmap.serialize(dataOutput)
    bout.toByteArray
  }
}
